<!--下载导入模板 上传短信模板-->
<template>
  <div class="si-add-template">
    <h2 class="title">{{$t('configLazyLoad.questionnaireConfig.importQues')}}</h2>
    <div class="wrap">
      <div class="instructions">
        <p v-html="$t('config.question.importInstructions')"></p>
        <div class="img-wrap">
        </div>
      </div>
      <div class="btn-wrap">
        <!--饿了么上传组件-->
        <el-upload
          class="temp-upload"
          :action="uploadUrl"
          name="upload"
          accept=".xls,.xlsx"
          :data="uploadHeaders"
          :with-credentials="true"
          :on-success="handleSuccess"
          :before-upload="beforeUpload"
          :show-file-list="false">
          <span>{{$t('configLazyLoad.questionnaireConfig.excelFile')}}：</span>
          <el-button size="mini">{{$t('configLazyLoad.questionnaireConfig.chooseFile')}}</el-button>
          <span style="margin-left: 10px">{{trueName}}</span>
        </el-upload>
    </div>
      <div  v-if="isShow" class="import-templ">
        <el-form label-position="top">
          <el-row>
            <el-col :span="24" class="padd-b-10">
              <el-form-item :label="$t('configLazyLoad.questionnaireConfig.quesTemp')">
                <el-select v-model="quesDb" :placeholder="$t('public.pleasePick')" @change="changeTemp">
                  <el-option
                    v-for="item in quesDbs"
                    :label="item.name"
                    :value="item._id">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="11" class="padd-b-10">
              <el-form-item :label="$t('configLazyLoad.questionnaireConfig.importBatch')">
                <el-input v-model.trim="batchNo" :disabled="true"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="11" :offset="2" class="padd-b-10">
              <el-form-item :label="$t('configLazyLoad.questionnaireConfig.batchDesc')">
                <el-input v-model.trim="beizhu"></el-input>
              </el-form-item>
            </el-col>
            <div class="padd-b-10 contact">{{$t('configLazyLoad.questionnaireConfig.chooseAssociation')}}</div>
            <el-col :span="11" :offset="index % 2 === 0 ? 0 : 2" v-for="(item, index) in heads" class="padd-b-10">
              <el-form-item :label="item.name">
                <el-select v-model="item.value" :placeholder="$t('public.pleasePick')">
                  <el-option
                    v-for="data in quesFields"
                    :label="data.name"
                    :value="data._id">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-button class="temp-download primary_btn fr" type="primary" @click.stop="submitImport()">
                {{$t('config.customer.import')}}
              </el-button>
            </el-col>
          </el-row>
        </el-form>
      </div>
    </div>
  </div>
</template>
<script>
  import Vue from 'vue'
  import { getDateNo, deepClone } from '@/utils/m7Utils.js'
  export default {
    name: 'quesImportAddTemplate',
    data () {
      return {
        trueName: '',
        fileName: '',
        isShow: false,
        beizhu: '',
        heads: [],
        quesDbs: [],
        quesDb: '',
        quesFields: [],
        batchNo: '',
        uploadUrl: '/fileUpload',
        uploadHeaders: {
          type: '',
          module: 'questionnaire',
          sessionId: this.$store.state.session.sessionId
        }
      }
    },
    methods: {
      // 提交导入的问卷
      submitImport () {
        let heads = []
        let name = 'name'
        this.heads.forEach((item) => {
          if (item.value) {
            heads.push(item.value)
          } else {
            heads.push('')
          }
        })
        if (heads.toString().indexOf(name) === -1) {
          this.$message.error(this.$t('config.customer.importContainCustomerName'))
          return false
        }
        let data = {
          fileName: this.fileName,
          trueName: this.trueName,
          dbType: this.quesDb,
          batchNo: this.batchNo,
          batchRemark: this.beizhu,
          heads: heads,
          dic: {},
          flag: 'start'
        }
        console.log(data)
        let p1 = this.$store.dispatch('quesConfigImport', data)
        Promise.all([p1]).then(([resp1]) => {
          console.log(resp1)
          this.$message.success(this.$t('configLazyLoad.questionnaireConfig.importSuccess'))
          let refreshLeft = {
            batchNo: this.batchNo,
            flag: 'refreshLeft'
          }
          this.$store.commit('config/questionnaireConfig/REFRESH_LEFT', refreshLeft)
        })
      },
//        上传前 配置上传参数
      beforeUpload (file) {
        let arr = file.name.split('.')
        let arrType = ['xls', 'xlsx']
        if (arrType.indexOf(arr[arr.length - 1]) !== -1) {
          return true
        } else {
          this.$message.error(this.$t('sms.uploadFileWrong'))
          return false
        }
      },
//      上传成功
      handleSuccess (response, file, fileList) {
        let fileName = response.filePath.split('/')
        this.batchNo = getDateNo()
        this.heads = []
        this.trueName = response.fileName
        this.fileName = fileName[fileName.length - 1]
        let data = {
          trueName: this.trueName,
          fileName: this.fileName
        }
        this.$store.dispatch('getQuesXlsHeads', data).then((resp) => {
          this.isShow = true
          resp.heads.forEach((item) => { // 用来自动匹配模板字段的
            let fieldItem = this.quesFields.filter(i => i.name === item)[0] // 过滤问卷模板看是否有跟导入的问卷模板匹配的字段
            let obj = {
              name: item,
              value: fieldItem ? fieldItem._id : ''
            }
            this.heads.push(obj)
          })
        })
      },
      changeTemp () { // 问卷调查模板改变是触发的方法
        this.quesFields = [] // 清空问卷模板
        this.heads.forEach((item) => {
          Vue.set(item, 'value', '')
        })
        let cache = this.$getCache('questionnaireField') || [] // 从缓存中获取问卷模板
        for (let i = 0; i < cache.length; i++) {
          var cacheItem = deepClone(cache[i])
          let relations = {}
          if (cacheItem.temp_id === this.quesDb) {
            let _key = cacheItem._id
            if (_key.indexOf('_name') !== -1) {
              relations['name'] = cacheItem.name
              relations['_id'] = 'name'
            } else if (_key.indexOf('_phone') !== -1) {
              relations['name'] = cacheItem.name
              relations['_id'] = 'phone'
            } else {
              relations['name'] = cacheItem.name
              relations['_id'] = cacheItem._id
            }
            this.quesFields.push(relations)
          }
        }
        this.heads.forEach((item) => { // 用来自动匹配模板字段的
          let fieldItem = this.quesFields.filter(i => i.name === item.name)[0] // 过滤问卷模板看是否有跟导入的问卷模板匹配的字段
          item.value = fieldItem ? fieldItem._id : ''
        })
      }
    },
    watch: {
    },
    activated () {
      let p1 = this.$store.dispatch('getCache', {type: 'questionnaireTemp'})
      let p2 = this.$store.dispatch('getCache', {type: 'questionnaireField'})
      Promise.all([p1, p2]).then(() => {
        let quesTmpls = this.$getCache('questionnaireTemp')
        if (quesTmpls.length) {
          this.quesDbs = quesTmpls
          this.quesDb = quesTmpls[0]._id
          this.changeTemp()
        }
      })
    },
    mounted () {
      let p1 = this.$store.dispatch('getCache', {type: 'questionnaireTemp'})
      let p2 = this.$store.dispatch('getCache', {type: 'questionnaireField'})
      Promise.all([p1, p2]).then(() => {
        let quesTmpls = this.$getCache('questionnaireTemp')
        if (quesTmpls[0]) {
          this.quesDbs = quesTmpls
          this.quesDb = quesTmpls[0]._id
          this.changeTemp()
        }
      })
    }
  }
</script>
<style lang="stylus" scoped>
  @import "../../../../../assets/common.styl"
  .title
    font-weight 600
  .el-form
    width 60%
    .el-form-item
      width 100%
      label
        width 200px !important
    .el-select
      width 100%
  .contact
    font-weight 500
    font-size 14px
  .si-add-template
    margin-left 341px
    height calc(100vh - 116px)
    padding-bottom 20px
    h2
      line-height 49px
      padding-left 20px
      font-size 14px
      color $cf-gray1
      border-bottom 1px solid #d9d9d9
    .import-templ
      .padd-b-10
        padding-bottom 10px
    .el-tabs__nav
      line-height 59px
    .wrap
      height calc(100vh - 252px)
      overflow auto
      padding 20px
      .btn-wrap
        padding-bottom 10px
        overflow hidden
        .temp-download
          float left
          background-color $c-sub
          border 1px solid $c-sub
          font-size 12px
          padding 6px
          a
            color #fff
        .temp-upload
          float left
          display inline-block
          margin-top 10px
          .temp-upload-btn
            background-color $c-main
            border 1px solid $c-main
            color #fff
            font-size 12px
            padding 6px
          .el-button
            height 20px
            padding 0 10px
      .instructions
        clear both
        font-size 12px
        line-height 22px
        color $c-prompt
      .img-wrap
        text-align center
</style>
